import { Card, Grid, List, Search, Image } from 'react-vant';
import './SearchPage.css';
import { use, useEffect, useState } from 'react';
import MyPromotePrice from '@/components/MyPromotePrice';
import { debounceAsync, getGoodsImagePath, getSaleCount } from '@/utils/common';
import { useNavigate } from 'react-router-dom';
import goodApi from '@/apis/goodApi';
import { ArrowLeft, Cross, DeleteO } from '@react-vant/icons';
import searchRecordApi from '@/apis/searchRecordApi';

const limit = 10;

const SearchPage: React.FC = () => {
  const [searchWord, setSearchWord] = useState<string>('');
  const [finished, setFinished] = useState<boolean>(false);
  const [goods, setGoods] = useState<ResponseGoodList[] | null>(null);
  const [page, setPage] = useState<number>(1);
  const [searchWords, setSearchWords] = useState<ResponseSearchRecordDto[] | null>(null);
  const [isDelete, setIsDelete] = useState<boolean>(false);
  const navigate = useNavigate();

  const fetchData = async () => {
    const res = await searchRecordApi.getAllSearchRecord();
    if (res.status >= 0) {
      setSearchWords(res.data);
    }
  };
  // 获取搜素记录
  useEffect(() => {
    fetchData();
  }, []);

  // 加载数据
  const onLoadMore = async () => {
    let res: ResponseApiDto = await goodApi.getGoodPagnation(page, limit, undefined, searchWord);
    if (res.status >= 0) {
      setGoods((prev) => [...(prev ?? []), ...res.data.data]);
      setPage((prev) => prev + 1);
      setFinished(res.data.data.length < limit);
    }
  };

  // 点击商品时跳转详情
  const handleProductClick = (id: number) => {
    navigate('/good/' + id);
  };

  const onSearchChange = debounceAsync(async (sw: string) => {
    setSearchWord(sw);
    setGoods([]);
    setPage(1);
    setFinished(false);
    // 添加搜素记录并刷新数据
    if (!sw.includes("'") && sw) {
      await searchRecordApi.addSearchRecord(sw);
      fetchData();
    }
  }, 500);

  const handleDelete = async (item: ResponseSearchRecordDto) => {
    const res = await searchRecordApi.deleteSearchRecord(item.id);
    if (res.status >= 0) {
      setSearchWords(searchWords?.filter((d) => d.searchWord != item.searchWord) ?? []);
    }
  };

  return (
    <>
      <div className="search-page-header">
        <div className="search-page-back">
          <ArrowLeft fontSize={'20px'} onClick={() => navigate(-1)} />
        </div>
        <Search
          className="search-page-search"
          shape="round"
          background="#4fc08d"
          value={searchWord}
          onChange={onSearchChange}
          placeholder="请输入商品名称"
        />
      </div>
      {searchWord.length === 0 ? (
        <>
          <div className="search-word-toggle-delete">
            {isDelete ? (
              <span onClick={() => setIsDelete(false)}>取消</span>
            ) : (
              <DeleteO fontSize={21} onClick={() => setIsDelete(true)} />
            )}
          </div>
          <div className="search-word-list">
            {searchWords?.map((d) => (
              <div
                key={d.id}
                className="search-word-item"
                onClick={() => setSearchWord(d.searchWord)}
              >
                {d.searchWord}
                {isDelete ? (
                  <Cross
                    color="gray"
                    className="search-word-item-icon"
                    onClick={(e) => {
                      e.stopPropagation();
                      handleDelete(d);
                    }}
                  />
                ) : null}
              </div>
            )) ?? null}
          </div>
        </>
      ) : (
        <List
          finished={finished}
          errorText="请求失败，点击重新加载"
          finishedText="没有更多了"
          onLoad={onLoadMore}
        >
          <Grid columnNum={2} border={false}>
            {goods?.map((item) => (
              <Grid.Item key={item.id}>
                <Card className="product-card" onClick={() => handleProductClick(item.id)}>
                  <Card.Body>
                    <div className="image-box">
                      <Image
                        src={getGoodsImagePath(item.id, item.photo)}
                        alt={item.name}
                        width="100%"
                        height="160"
                        lazyload
                      />
                    </div>
                    <div className="product-info">
                      <h3>{item.name}</h3>
                      <div className="spec-section">{item.spec}</div>
                      <div className="price-section">
                        <MyPromotePrice price={item.price} propmotePrice={item.promotePrice} />
                      </div>
                      <div className="sales">已售{getSaleCount(item.saleCout)}份</div>
                    </div>
                  </Card.Body>
                </Card>
              </Grid.Item>
            )) ?? null}
          </Grid>
        </List>
      )}
    </>
  );
};

export default SearchPage;
